package com.crazymakercircle.buffer;

import org.junit.Test;

import java.nio.IntBuffer;

/**
 * @author
 */

public class UseBuffer {
    static IntBuffer intBuffer = null;

    /**
     * 分配内存，实例化对象
     */
    //@Test
    public static void allocateTest() {
        UseBuffer.intBuffer = IntBuffer.allocate(20);
        System.out.println("----allocate-----");
        System.out.println("position=" + intBuffer.position());
        System.out.println("limit=" + intBuffer.limit());
        System.out.println("capacity=" + intBuffer.capacity());
    }

    /**
     * 写入数据
     */
    //@Test
    public static void putTest() {
        //allocateTest();
        for (int i = 0; i < 5; i++) {
            intBuffer.put(i);
        }
        System.out.println("--------put--------");
        System.out.println("position=" + intBuffer.position());
        System.out.println("limit=" + intBuffer.limit());
        System.out.println("capacity=" + intBuffer.capacity());
    }

    /**
     * 写模式翻转成读模式
     */
//    @Test
    public static void flipTest() {
//        allocateTest();
//        putTest();
        intBuffer.flip();
        System.out.println("----flip-----");
        System.out.println("position=" + intBuffer.position());
        System.out.println("limit=" + intBuffer.limit());
        System.out.println("capacity=" + intBuffer.capacity());
    }

    /**
     * 从缓冲区读取数据
     */
    public static void getTest(){
        for (int i = 0; i < 2; i++) {
            int j = intBuffer.get();
            System.out.println("j=" + j);
        }
        System.out.println("--------after get 2 int-----------");
        System.out.println("position=" + intBuffer.position());
        System.out.println("limit=" + intBuffer.limit());
        System.out.println("capacity=" + intBuffer.capacity());
        for (int i = 0; i < 4; i++) {
            int j = intBuffer.get();
            System.out.println("j=" + j);
        }
        System.out.println("--------after get 3 int-----------");
        System.out.println("position=" + intBuffer.position());
        System.out.println("limit=" + intBuffer.limit());
        System.out.println("capacity=" + intBuffer.capacity());
    }

    public static void rewindTest(){
        intBuffer.rewind();
        System.out.println("-----------after rewind----------");
        System.out.println("position="+intBuffer.position());
        System.out.println("limit="+intBuffer.limit());
        System.out.println("capacity="+intBuffer.capacity());
    }

    public static void main(String[] args) {
        allocateTest();
        putTest();
        flipTest();
        getTest();
    }
}
